<script setup lang="ts">
import {computed, ref, onMounted} from 'vue'
import axios from 'axios'
import {ElMessage, ElMessageBox, type UploadProps} from 'element-plus'

/**
 * 弹窗状态
 */
const dialogVisibleDel = ref(false)//删除弹窗
const dialogVisible = ref(false)//新增弹窗
const dialogVisibleEdit = ref(false)//编辑弹窗
const currentDeleteEmployee = ref<Employee | null>(null) // 新增：存储当前要删除的员工
const currentEditEmployee = ref<Partial<Employee>>({
  name: '',
  position: 0,
  photo: '',
  description: ''
})
//新员工容器
const newEmployee = ref<Partial<Employee>>({
  name: '',
  position: 0,
  photo: '',
  description: ''
})
const formatPosition = (position: number) => {
  const map = {
    0: '初级技工',
    1: '中级技工',
    2: '高级技工',
    3: '专家'
  }as Record<number, string>
  return map[position] || '未知职级'
}
//头像上传
interface Employee {
  id: number
  jobNumber: number
  name: string
  photo: string
  position: number
  formattedEntryDate: string
  description?: string
}

const photoPreviewUrl = ref('')
const uploadedFile = ref<File | null>(null)
const search = ref('')
const employees = ref<Employee[]>([]) // 存储员工数据
const loading = ref(false) // 加载状态


// 获取员工列表
const fetchEmployees = async () => {
  try {
    loading.value = true
    const response = await axios.get('/api/staff/list')
    employees.value = response.data.data || []
  } catch (error) {
    console.error('获取员工列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 筛选员工数据
const filterTableData = computed(() =>
    employees.value.filter(
        (data) =>
            !search.value ||
            data.name.toLowerCase().includes(search.value.toLowerCase())
    )
)

const submitEditEmployee = async () => {
  try {
    loading.value = true
    const formData = new FormData()
    formData.append('id', currentEditEmployee.value.id!.toString())
    formData.append('name', currentEditEmployee.value.name || '')
    formData.append('position', currentEditEmployee.value.position!.toString())
    formData.append('description', currentEditEmployee.value.description || '')

    if (uploadedFile.value) {
      formData.append('photo', uploadedFile.value)
    }

    await axios.post('/api/staff/update', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    ElMessage.success('修改成功')
    await fetchEmployees()
    dialogVisibleEdit.value = false
    photoPreviewUrl.value = ''
    uploadedFile.value = null
  } catch (error) {
    ElMessage.error('修改失败')
  } finally {
    loading.value = false
  }
}
const handleEdit = (index: number, row: Employee) => {
  currentEditEmployee.value = {
    name: row.name,
    description: row.description,
    id: row.id,
    photo: row.photo,
    position: row.position
  }
  // 添加预览图片初始化
  photoPreviewUrl.value = row.photo ? `${row.photo}` : '' // 根据实际后端配置调整路径
  dialogVisibleEdit.value = true
  console.log(photoPreviewUrl.value)
}
const handleDelete = (index: number, row: Employee) => {
  currentDeleteEmployee.value = row
  dialogVisibleDel.value = true
  console.log(index, row)
}
const handleAddEmployee = () => {
  dialogVisible.value = true
}
//新增员工逻辑
const submitAddEmployee = async () => {
  try {
    loading.value = true
    const formData = new FormData()
    formData.append('name', newEmployee.value.name || '')
    formData.append('position', newEmployee.value.position!.toString())
    formData.append('description', newEmployee.value.description || '')
    if (uploadedFile.value) {
      formData.append('photo', uploadedFile.value) // 确保字段名与后端一致（可能是file/photo）
    }

    await axios.post('/api/staff/add', formData, {
      headers: {
        'Content-Type': 'multipart/form-data' // 添加正确的请求头
      }
    })
    ElMessage.success('新增成功')
    await fetchEmployees()
    dialogVisible.value = false
    newEmployee.value = {name: '', position: 0, photo: '',description:''}
    photoPreviewUrl.value = '' // 清空预览图
    uploadedFile.value = null
  } catch (error) {
    ElMessage.error('新增失败')
  } finally {
    loading.value = false
  }
}

const handleUploadSuccess = (response: any, uploadFile: any) => {
  if (response.code === 200) {
    photoPreviewUrl.value = response.data.url
    uploadedFile.value = uploadFile.raw
  }
}
const handleFileChange = (file: any) => {
  photoPreviewUrl.value = URL.createObjectURL(file.raw)
  uploadedFile.value = file.raw
}
// 组件挂载时获取数据
onMounted(() => {
  fetchEmployees()
})

/**
 * 删除员工
 */
const confirmDelete = async () => {
  if (!currentDeleteEmployee.value) return

  try {
    loading.value = true
    await axios.delete(`/api/staff/delete?id=${currentDeleteEmployee.value.id}`)
    ElMessage.success('删除成功')
    await fetchEmployees() // 重新获取员工列表
  } catch (error) {
    console.error('删除员工失败:', error)
    ElMessage.error('删除失败')
  } finally {
    loading.value = false
    dialogVisibleDel.value = false
    currentDeleteEmployee.value = null
  }
}
//校验图片
const beforePhotoUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (!['image/jpeg', 'image/png'].includes(rawFile.type)) {
    ElMessage.error('头像必须是 JPG/PNG 格式!')
    return false
  }
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }
  return true
}
// 新增筛选职位
const selectedPosition = ref<number | null>(null)

// 修改后的筛选逻辑
const filterTableData2 = computed(() =>
    employees.value.filter(
        (data) =>
            (!search.value || data.name.toLowerCase().includes(search.value.toLowerCase())) &&
            (selectedPosition.value === null || data.position === selectedPosition.value)
    )
)
</script>

<template>
  <div class="employee-management">
    <div class="wrap">
      <el-table
          :data="filterTableData2"
          style="width: 100%"
          v-loading="loading"
      >
        <el-table-column label="工号" prop="jobNumber"/>
        <el-table-column label="姓名" prop="name"/>
        <el-table-column label="职级" prop="position">
          <template #header>
            <div style="display: flex; align-items: center; gap: 5px">
              <span>职级</span>
              <el-select
                  v-model="selectedPosition"
                  placeholder="全部"
                  clearable
                  size="small"
                  style="width: 120px"
              >
                <el-option label="初级技工" :value="0" />
                <el-option label="中级技工" :value="1" />
                <el-option label="高级技工" :value="2" />
                <el-option label="专家" :value="3" />
              </el-select>
            </div>
          </template>
          <template #default="{ row }">
            {{ formatPosition(row.position) }}
          </template>
        </el-table-column>
        <el-table-column label="入职时间" prop="formattedEntryDate"/>
        <el-table-column align="right">
          <template #header>
            <div style="display: flex; align-items: center; justify-content: flex-end; gap: 5px">
              <el-input
                  v-model="search"
                  size="small"
                  placeholder="搜索员工"
                  style="width: 300px;"
              />
              <el-button
                  type="primary"
                  size="small"
                  @click="handleAddEmployee"
              >
                新增员工
              </el-button>
            </div>
          </template>
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
              编辑
            </el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
  <!--新增员工弹窗-->
  <el-dialog
      v-model="dialogVisible"
      title="新增员工"
      width="400"
      class="addEmployeeDialog"
  >
    <el-form :model="newEmployee" label-width="80px">
      <el-form-item label="头像">
        <el-upload
            class="avatar-uploader"
            :auto-upload="false"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :on-change="handleFileChange"
            :before-upload="beforePhotoUpload"
        >
          <el-avatar
              :size="120"
              shape="square"
              :src="photoPreviewUrl || newEmployee.photo || 'https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png'"/>
          <el-button class="upload-tip" type="primary" size="small" style="margin-left: 10px;">
            点击上传
          </el-button>
        </el-upload>
      </el-form-item>

      <el-form-item label="姓名">
        <el-input v-model="newEmployee.name" placeholder="请输入员工姓名"/>
      </el-form-item>

      <el-form-item label="职级">
        <el-select v-model="newEmployee.position" placeholder="请选择职级">
          <el-option label="初级技工" :value="0"/>
          <el-option label="中级技工" :value="1"/>
          <el-option label="高级技工" :value="2"/>
          <el-option label="专家" :value="3"/>
        </el-select>
      </el-form-item>
      <el-form-item label="描述">
        <el-input type="textarea" v-model="newEmployee.description" placeholder="请输入描述"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddEmployee">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!--  编辑员工弹窗-->
  <el-dialog
      v-model="dialogVisibleEdit"
      title="编辑员工信息"
      width="400"
      class="addEmployeeDialog"
  >
    <el-form :model="currentEditEmployee" label-width="80px">
      <el-form-item label="头像">
        <el-upload
            class="avatar-uploader"
            :auto-upload="false"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :on-change="handleFileChange"
            :before-upload="beforePhotoUpload"
        >
          <el-avatar
              :size="120"
              shape="square"
              :src="photoPreviewUrl || (currentEditEmployee.photo ? `/api${currentEditEmployee.photo}` : '')"/>
          <el-button class="upload-tip" type="primary" size="small" style="margin-left: 10px;">
            点击上传
          </el-button>
        </el-upload>
      </el-form-item>

      <el-form-item label="姓名">
        <el-input v-model="currentEditEmployee.name" placeholder="请输入员工姓名"/>
      </el-form-item>

      <el-form-item label="职级">
        <el-select v-model="currentEditEmployee.position" placeholder="请选择职级">
          <el-option label="初级技工" :value="0"/>
          <el-option label="中级技工" :value="1"/>
          <el-option label="高级技工" :value="2"/>
          <el-option label="专家" :value="3"/>
        </el-select>
      </el-form-item>
      <el-form-item label="描述">
        <el-input type="textarea" v-model="currentEditEmployee.description" placeholder="请输入描述"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisibleEdit = false">取消</el-button>
        <el-button type="primary" @click="submitEditEmployee">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!--  删除员工弹窗-->
  <el-dialog
      v-model="dialogVisibleDel"
      title="⚠️警告"
      width="300"
  >
    <span>确定要删除员工 {{ currentDeleteEmployee?.name }} 吗？</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete" :loading="loading">
          删除
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.employee-management {
  .wrap {
    .el-table {
      border-radius: 10px;
    }
  }
}

</style>